"""
按周期计算收益率，简单方法
"""
import pandas as pd
import numpy as np
class rank:
    def __init__(self,box=None,ascending=False):
        self.box=box
        self.ascending=ascending
    def oncalc(self,d,timekey=None):
        f=d.copy()
        f.sort_values(ascending=self.ascending,inplace=True)
        f1=f.isna()
        n=len(f)+1
        f=pd.Series(data=list(range(1,n)),index=f.index)
        f.loc[f1] = np.nan
        if self.box:
            min0=f.min()
            max0=f.max()
            f=(f-min0)/(max0-min0)
            if self.box !=[0,1]:
                f=f*(self.box[1]-self.box[0])+self.box[0]
        return f

if __name__ == '__main__':
    from jili.dataset import dataset
    from research.calcor.calcors_graph import graph_calcor,graph_calcor_axis1
    cc = [{'calc_cmd': 'class', "class": "ror", "out": ["ror10"], "init_args": {"timeperiod": 10},"input":["close"]}]

    cc1 = [{'calc_cmd': 'class', "class": "rank", "out": ["rank0"],"input":["ror10"],"init_args": {"box":None},"index":"obj","in_isdf":True,"out_isdf":True},
           {'calc_cmd': 'class', "class": "rank", "out": ["rank1"], "input": ["ror10"], "init_args": {"box": [0,1]},
            "index": "obj", "in_isdf": True, "out_isdf": True},
           {'calc_cmd': 'class', "class": "rank", "out": ["rank2"], "input": ["ror10"], "init_args": {"box": [0,100]},
            "index": "obj", "in_isdf": True, "out_isdf": True}
           ]
    c1 = graph_calcor_axis1(cc1)
    datatool0 = dataset(product="stock", datatype="k1d", baseurl=r"G:\price", region="C", fqtype="hfq",
                        source=None)
    pretk=None
    data={}
    data1={}
    stock_c={}
    for _,t in datatool0.iter_price("all", "20200103"):
        tk=t["timekey"]
        obj=t["obj"]
        if pretk:
            if pretk!=tk:
                data1=c1.onbar(data)
                data={}
                pretk=tk
        else:
            pretk=tk
        if obj not in stock_c.keys():
            stock_c[obj]= graph_calcor(cc)
        t=stock_c[obj].onbar(t)
        data[obj]=t

